<?php

namespace app\admin\model;

use think\Exception;
use think\Model;
use app\admin\validate\Section as SectionValidate;

class Section extends Model {

    private $success_code = 'suc';
    private $error_code = 'err';
    protected $insert = ['status','is_recommended','create_time','update_time'];
    protected $update = ['status','is_recommended','update_time'];

    public function saveData($data,$action,$id = ''){
        //实例化验证器
        $validate = new SectionValidate();
        //验证器验证
        if (!$validate->check($data)){
            return ['code' => $this->error_code,'msg' => $validate->getError()];
        }

        $repeat = son_repeat('section',$data['pid'],$data['name'],$id);
        if ($repeat){
            return ['code' => 'err', 'msg' => '当前栏目下已存在' . $data['name']];
        }
        $data['level'] = $this->level(intval($data['pid'])) + 1;
        if ($action == 'add'){
            return $this->add($data);
        }elseif ($action == 'edit'){
            return $this->edit($id,$data);
        }

    }

    public function add($data){
        try{
            $result = self::allowField(true)->create($data);
            if ($result){
                insert_system_log('添加栏目：' . $result);
                return ['code' => $this->success_code,'msg' => config('msg.add_suc')];
            }
            return ['code' => $this->error_code,'msg' => config('msg.err_msg')];
        }catch (Exception $e){
            return ['code' => 'err', 'msg' => $e->getMessage()];
        }

    }

    public function edit($id,$data){
        try{
            $result = self::save($data, ['id' => $id]);
            if ($result){
                insert_system_log('修改栏目：' . $id);
                return ['code' => $this->success_code,'msg' => config('msg.edit_suc')];
            }
            return ['code' => $this->error_code,'msg' => config('msg.err_msg')];
        }catch (Exception $e){
            return ['code' => 'err', 'msg' => $e->getMessage()];
        }
    }

    public function delData($id){
        //查询是否有子级
        $son = $this->db('section')
            ->where('pid',$id)
            ->select();
        //如果有子级，连同子级一起删除
        if (!empty($son)){
            $son_ids = [];
            foreach ($son as $v){
                array_push($son_ids,intval($v['id']));
            }
            array_push($son_ids,$id);
        }else{
            $son_ids[] = $id;
        }
        $result = db('section')->where('id','in',$son_ids)->delete();
        if ($result){
            return ['code' => 'suc', 'msg' => '已删除'];
        }else{
            return ['code' => 'err', 'msg' => '删除失败'];
        }
    }

    public function level($pid,$level = 0){

        if ($pid !== 0){
            $level++;

            $parent = $this->db('section')
                ->where('id',$pid)
                ->field('id,pid')
                ->find();
            if ($parent['pid'] !== 0){
                $level = $this->level($parent['pid'],$level);
            }
        }

        return $level;
    }

    protected function setStatusAttr($value){
        return empty($value) ? 0 : 1;
    }

    protected function setIsRecommendedAttr($value){
        return empty($value) ? 0 : 1;
    }

    protected function setCreateTimeAttr(){
        return time();
    }

    protected function setUpdateTimeAttr(){
        return time();
    }
}